package Arrays;

/**
 * 作者:hfj
 * 功能:67.二进制求和
 * 日期: 2025/10/21 20:52
 */
public class AddBinary {
    public static void main(String[] args) {
        String a = "1";
        String b = "111";
        System.out.println(addBinary(a,b));
    }
    //如果转成整形在转二进制会遇到整形溢出问题
    public static String addBinary(String a, String b) {
        int[] num_a = new int[a.length()];
        int[] num_b = new int[b.length()];
        for (int i = 0; i < a.length(); i++) {
            num_a[i] = Character.getNumericValue(a.charAt(i));
        }
        for (int i = 0; i < b.length(); i++) {
            num_b[i] = Character.getNumericValue(b.charAt(i));
        }
        String res = "";
        int len_a = num_a.length-1,len_b = num_b.length-1,temp = 0;//进位临时变量
        //解题思想:利用临时变量存储进位,从左向右遍历最后在反转字符串
        while (len_a >= 0 && len_b >= 0){
            int sum = num_a[len_a] + num_b[len_b] + temp;
            if (sum <= 1){
                res += sum;
                temp = 0;
            } else if (sum == 2) {
                res += 0;
                temp=1;
            } else if (sum == 3) {
                res += 1;
                temp=1;
            }
            len_a--;
            len_b--;
        }
        while (len_a >= 0){
            int sum = num_a[len_a] + temp;
            if (sum <= 1){
                res += sum;
                temp = 0;
            } else if (sum == 2) {
                res += 0;
                temp=1;
            } else if (sum == 3) {
                res += 1;
                temp=1;
            }
            len_a--;
        }
        while (len_b >= 0){
            int sum = num_b[len_b] + temp;
            if (sum <= 1){
                res += sum;
                temp = 0;
            } else if (sum == 2) {
                res += 0;
                temp=1;
            } else if (sum == 3) {
                res += 1;
                temp=1;
            }
            len_b--;
        }
        if (temp == 1){
            res += 1;
        }
        String reversed = new StringBuilder(res).reverse().toString();
        return reversed;
    }

}
